from .models import Article,Comment,CollectArticleModel
from rest_framework import serializers
from users.serializer import UserSummarySerializer
from utils.dfa import get_dfa


class ArticleListSerializers(serializers.ModelSerializer):
    author = UserSummarySerializer()
    publish_date = serializers.DateTimeField(read_only=True,format="%Y-%m-%d %H:%M")
    comments = serializers.IntegerField(source="comments.count",read_only=True)
    like_nums = serializers.IntegerField(read_only=True,source="collect.count",default=0)

    class Meta:
        model = Article
        fields = "__all__"


class ArticleCreateSerializers(serializers.ModelSerializer):
    author = serializers.HiddenField(default=serializers.CurrentUserDefault())

    class Meta:
        model = Article
        fields = "__all__"

    def validate(self, attrs):
        attrs["title"] = get_dfa(attrs["title"])
        attrs["content"] = get_dfa(attrs["content"])
        return attrs


class BlogCommentListSerializers(serializers.ModelSerializer):
    user = UserSummarySerializer()
    date = serializers.DateTimeField(read_only=True,format="%Y-%m-%d %H:%M")

    class Meta:
        model = Comment
        fields = "__all__"


class BlogCommentCreateSerializers(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    date = serializers.DateTimeField(read_only=True,format="%Y-%m-%d %H:%M")

    class Meta:
        model = Comment
        fields = "__all__"

    def validate(self, attrs):
        attrs["comment"] = get_dfa(attrs["comment"])
        return attrs


class CollectSerializers(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())

    class Meta:
        model = CollectArticleModel
        fields = "__all__"


class CollectListSerializers(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    article = ArticleListSerializers(read_only=True)
    class Meta:
        model = CollectArticleModel
        fields = "__all__"

